package org.esk.dablog.web.forms;

import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.ModelAndView;
import org.esk.dablog.service.EntryManager;
import org.esk.dablog.model.Entry;
import org.esk.dablog.web.util.ListRandomAccess;
import org.esk.dablog.ApplicationConstants;
import org.apache.commons.lang.math.NumberUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Properties;

/**
 * This class
 * User: jc
 * Date: 22.11.2006
 * Time: 11:11:40
 * $Id:$
 */
public class HomePageForm extends ParameterizableViewController {
    private static final String PARAMETER_SKIP = "skip";
    private static final int TOPLINE_COUNT = 5;

    private EntryManager entryManager;
    private Properties entryRenderers;
    private List<Class<? extends Entry>> normalModeEntries;
    private List<Class<? extends Entry>> topLineEntries;


    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        int skip = NumberUtils.toInt(request.getParameter(PARAMETER_SKIP));
        int portion = ApplicationConstants.getInstance().getDefaultPortion();
        ModelAndView result = new ModelAndView(getViewName());

        List<Entry> entries = entryManager.listEntries(normalModeEntries, skip, portion);
        if (skip <= 0) {
            List<Entry> topLine = entryManager.listEntries(topLineEntries, 0, TOPLINE_COUNT);
            result.addObject("topLine", topLine);
        }
        result.addObject("randomizer", new ListRandomAccess());
        result.addObject("entries", entries);
        result.addObject("renderers", entryRenderers);
        return result;
    }

    public void setEntryManager(EntryManager entryManager) {
        this.entryManager = entryManager;
    }


    public void setEntryRenderers(Properties entryRenderers) {
        this.entryRenderers = entryRenderers;
    }


    public void setNormalModeEntries(List<Class<? extends Entry>> normalModeEntries) {
        this.normalModeEntries = normalModeEntries;
    }

    public void setTopLineEntries(List<Class<? extends Entry>> topLineEntries) {
        this.topLineEntries = topLineEntries;
    }
}
